# -*- coding: utf-8 -*-

import pytest

from appium import webdriver
from appium.options.android import UiAutomator2Options
from appium.webdriver.appium_service import AppiumService
from appium.webdriver.common.appiumby import AppiumBy

import time

# 开启服务端
APPIUM_HOST = '127.0.0.1'
APPIUM_PORT = 4723
@pytest.fixture(scope="session")
def start_appium_service():
    server = AppiumService()
    server.start(args=['--address', APPIUM_HOST, '-p', str(APPIUM_PORT)], timeout_ms=60000)
    yield server
    server.stop()

# 创建客户端到服务端的会话
def create_appium_session_by_api(custom_opts = None):
    options = UiAutomator2Options()
    if custom_opts is not None:
        options.load_capabilities(custom_opts)
    return webdriver.Remote(f'http://{APPIUM_HOST}:{APPIUM_PORT}', options=options)

# 通过资源id定位元素
def test_find_element_by_id(start_appium_service):
    custom_opts = {
        "appPackage": "com.google.android.dialer",
        "appActivity": ".extensions.GoogleDialtactsActivity"
    }
    driver = create_appium_session_by_api(custom_opts)

    # 全id名
    contact_id_full = "com.google.android.dialer:id/tab_contacts"
    contact = driver.find_element(AppiumBy.ID, value=contact_id_full)
    assert contact

    # 短id名
    contact_id_short = "tab_contacts"
    contact = driver.find_element(AppiumBy.ID, contact_id_short)
    assert contact

# 通过内容描述定位元素
def test_find_element_by_accessibilityId(start_appium_service):
    custom_opts = {
        "appPackage": "com.google.android.dialer",
        "appActivity": ".extensions.GoogleDialtactsActivity"
    }
    driver = create_appium_session_by_api(custom_opts)

    # 内容描述
    contact_content_desc = "Contacts"
    contact = driver.find_element(AppiumBy.ACCESSIBILITY_ID, value=contact_content_desc)
    assert contact

# 通过类型查找
def test_find_element_by_class(start_appium_service):
    custom_opts = {
        "appPackage": "com.google.android.dialer",
        "appActivity": ".extensions.GoogleDialtactsActivity"
    }
    driver = create_appium_session_by_api(custom_opts)

    # 类型名称
    contact_class = "android.widget.FrameLayout"
    contact = driver.find_elements(AppiumBy.CLASS_NAME, value=contact_class)
    content_desc = "Contacts"
    find_contact_flag = False
    for element in contact:
        try:
            if element.get_attribute('content-desc') == content_desc:
                find_contact_flag = True
        except:
            pass

    assert find_contact_flag


# 通过'-android uiautomator'查找
def test_find_element_by_android_uiautomator(start_appium_service):
    custom_opts = {
        "appPackage": "com.google.android.dialer",
        "appActivity": ".extensions.GoogleDialtactsActivity"
    }
    driver = create_appium_session_by_api(custom_opts)

    # 选择以类型名称查找：可以指定序号返回找到的元素实例，下面的调用即指定返回第3个找到的实例
    contact = driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, value='new UiSelector().className("android.widget.FrameLayout").instance(2)')
    assert contact.get_attribute("class") == "android.widget.FrameLayout"

    # 选择以文本内容查找
    contact = driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, value='new UiSelector().text("Contacts")')
    assert contact.get_attribute("text") == "Contacts"

    # 选择以资源id查找
    contact = driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, value='new UiSelector().resourceId("com.google.android.dialer:id/tab_contacts")')
    assert contact.get_attribute("resource-id") == "com.google.android.dialer:id/tab_contacts"

    # 选择以内容描述查找
    contact = driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, value='new UiSelector().description("Contacts")')
    assert contact.get_attribute("content-desc") == "Contacts"


# 通过'-android uiautomator'查找，组合方式查找
def test_find_element_by_android_uiautomator_combine(start_appium_service):
    custom_opts = {
        "appPackage": "com.google.android.dialer",
        "appActivity": ".extensions.GoogleDialtactsActivity"
    }
    driver = create_appium_session_by_api(custom_opts)

    # 先以className筛选出元素，然后从中以content-desc匹配
    contact = driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, value='new UiScrollable(new UiSelector().className("android.widget.FrameLayout")).scrollIntoView(new UiSelector().description("Contacts"))')
    assert contact.get_attribute("resource-id") == "com.google.android.dialer:id/tab_contacts"


# 通过'-android uiautomator'查找，使用滑动操作
def test_find_element_by_android_uiautomator_scroble(start_appium_service):
    custom_opts = {
        "appPackage": "com.google.android.dialer",
        "appActivity": ".extensions.GoogleDialtactsActivity"
    }
    driver = create_appium_session_by_api(custom_opts)

    contact = driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, value='new UiSelector().resourceId("com.google.android.dialer:id/tab_contacts")')
    assert contact.get_attribute("resource-id") == "com.google.android.dialer:id/tab_contacts"
    contact.click()

    create_new_contact = driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, value='new UiSelector().text("Create new contact")')
    create_new_contact.click()
    time.sleep(1)

    # 将Home标签表示的元素滚动到可视范围
    # scroble_to_home_label = driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiScrollable(new UiSelector().scrollable(true).instance(0)).getChildByText(new UiSelector().className("android.widget.Spinner"), "Home")')
    scroble_to_home_label_2 = driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector().text("Home").instance(0))')


# 通过'xpath'查找
def test_find_element_by_xpath(start_appium_service):
    custom_opts = {
        "appPackage": "com.google.android.dialer",
        "appActivity": ".extensions.GoogleDialtactsActivity"
    }
    driver = create_appium_session_by_api(custom_opts)

    # xpath查找
    contact = driver.find_element(AppiumBy.XPATH, value='//android.widget.FrameLayout[@content-desc="Contacts"]')
    assert contact.get_attribute("resource-id") == "com.google.android.dialer:id/tab_contacts"
